<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>JS计算字符宽高</title>
    </head>
    <body>
        <!-- <canvas id="canvas" width="200" height="200"></canvas> -->
        <script>
            //利用span
            let span = document.createElement("span")
            span.style.positon = "ablsolute"

            function getCharSize(char, style = {}){
                let {
                    fontSize = 14,
                    fontFamily = "SimSun"
                } = style
                
                let scale = fontSize / 20
                span.style.fontSize = "20px"
                span.style.fontFamily = fontFamily
                span.style.lineHeight = "0"
                span.style.transform = `scale(${scale})`
                span.style.display = "inline-block"
                span.innerHTML = char
                document.body.appendChild(span)
                let rect = span.getBoundingClientRect()
                let width = rect.width
                document.body.removeChild(span)
                return {
                    width,
                    height: fontSize
                }
            }

            //利用Canvas
            let canvas = document.createElement('canvas')
            canvas.style.positon = "ablsolute"
            let ctx = canvas.getContext('2d')

            function getCharSizeByCanvas(char, style = {}){
                let {
                    fontSize = 14,
                    fontFamily = "Arial"
                } = style
                // document.body.appendChild(canvas)
                ctx.font = `${fontSize}px ${fontFamily}`
                // document.body.removeChild(canvas)
                let text = ctx.measureText(char) // TextMetrics object
                console.log(text)
                ctx.fillText(char, 50, 50)
                let result = {
                    height: fontSize,
                    width: text.width
                }
                return result
            }

            getCharSizeByCanvas("啊ass")

            // 性能比较
            // let str = "我"
            
            // const COUNT = 100000
    
            // let startTime = Date.now()
            // for(let i = 0; i < COUNT; i++){
            //     getCharSize(str)
            // }
            // let endTime = Date.now()
            // console.log("方法一：", (endTime - startTime) + 'ms')
    
            // startTime = Date.now()
            // for(let i = 0; i < COUNT; i++){
            //     getCharSizeByCanvas(str)
            // }
            // endTime = Date.now()
            // console.log("方法二：", (endTime - startTime) + 'ms')
        </script>
    </body>
</html>